import { getImgUrl, jumpUrl, useUrlParams } from '@/utils';
import { Button, Card, Col, Collapse, Flex, Form, Space, message } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { Helmet, getLocale, useIntl, useModel } from 'umi';

import arrow from '@/assets/center_arrow.png';

import Layout from '@/components/Layouts';
import { getProductConfig, handleApplyOrder, handleGetToken } from '@/services/center';
import { editOrder, editPage, findByCodeList } from '@/services/login';
import { useRequest } from 'ahooks';

import StepLive from '../Info/components/StepLive';
import StepOne from '../Info/components/StepOne';
import StepThree from '../Info/components/StepThree';
import StepTwo from '../Info/components/StepTwo';

import banner from '@/assets/baner4.png';
import userIcon from '@/assets/s_1.png';
import workIcon from '@/assets/s_2.png';
import moneyIcon from '@/assets/s_3.png';
import imgIcon from '@/assets/s_4.png';
import dayjs from 'dayjs';
import UploadList from '../Info/components/UploadList';
import '../PersonCenter/index.less';

import TopInfo from '@/components/TopInfo';
import ApplySucModal from '../Product/components/ApplySucModal';

const Supplement: React.FC = () => {
  const { user, run } = useModel('userModel');
  const isEn = getLocale() == 'en-US';

  const intl = useIntl();
  const { setKey } = useModel('stepModel');
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);

  const id = useUrlParams('id');

  // 从我的订单页面来
  const order = useUrlParams('order');
  const orderId = useUrlParams('orderId');
  const loanAmount = useUrlParams('loanAmount');
  const loanTerm = useUrlParams('loanTerm');
  const { data } = useRequest(() => getProductConfig({ pid: id }));
  const { uploadParams } = useModel('uploadModel');

  const { productConfig: supplementList, productInfo } = data?.data || {};
  const { data: productOptions } = useRequest(() =>
    findByCodeList({ code: 'productType,livingSituation,occupation' }),
  );
  const {
    productType,
    livingSituation: livingSituationList,
    occupation: occupationList,
  } = productOptions?.data || {};
  const { livingSituation, occupation } = user;

  const [form] = Form.useForm();
  const value = Form.useWatch([], form);
  useEffect(() => {
    const value = user || {};
    if (Object.keys(value)?.length > 0) {
      const {
        addressProof,
        bankMonthlyStatement,
        workProof,
        vehicleProof,
        estateProof,
        stockProof,
        cryptocurrencyProof,
        insuranceProof,
        otherProof,
        creditProof,
        birthday,
        graduationTime,
        userWorkInfo,
        loanInfo,
        idCardImg,
        idCardImg1,
        statementsConfirmFlag,
        ...rest
      } = value;
      // 设置表单用于二级联动的情景
      form.setFieldsValue({
        ...rest,
      });
    }
  }, [user, form]);
  // 额外文字
  const genExtra = (num: number) => {
    return (
      <span style={{ color: '#666' }}>
        {intl.formatMessage(
          { id: isEn ? (num > 1 ? 'home.supplement1' : 'home.supplement') : 'home.supplement' },
          { num: <span style={{ color: '#0270DF' }}>{num}</span> },
        )}
      </span>
    );
  };
  useEffect(() => {
    setKey(
      supplementList?.filter((item) => item.positionId != '5')?.map((item) => item.key) as any,
    );
  }, [supplementList, setKey]);
  // 过滤掉图片资料
  const filterList = supplementList
    ?.filter((item) => item.positionId == '5')
    .map((item) => {
      const { key, keyDesc, keyDescEn } = item;
      return {
        profileName: isEn ? keyDescEn : keyDesc,
        defaultValue: key == 'idCardImg' ? 'idCard' : key,
      };
    });
  const renderBtn = (word?: string) => {
    return (
      <Form.Item noStyle>
        <Button
          type="primary"
          loading={loading}
          htmlType="submit"
          style={{
            height: '60px',
            minWidth: 360,
            display: 'flex',
            border: 'none',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto',
          }}
        >
          <div style={{ fontSize: 16, color: '#fff' }}>
            {intl.formatMessage({ id: word || 'home.save' })}
          </div>
        </Button>
      </Form.Item>
    );
  };

  const handleVal = (val: any, key: string) => {
    const type = Object.prototype.toString.call(val);

    if (type == '[object Array]') {
      return key == 'insuranceProof'
        ? val?.filter((item: any) => Object.keys(item).length > 0).length > 0
        : val?.filter((item: any) => item.url).length > 0;
    } else if (type == '[object Object]') {
      return Object.values(val).every((item) => item);
    }
    return val;
  };
  const items = useMemo(() => {
    const ids = [...new Set(supplementList?.map((item) => item.positionId))];
    const returnNumber = (list: any) => {
      return list?.filter((item: any) => {
        const { key } = item;
        return !value[key];
      }).length;
    };
    // 图片不一样
    const renderImgNumber = () => {
      const { statementsConfirmFlag } = uploadParams;
      return filterList?.filter((item: any) => {
        const { defaultValue } = item;
        const val =
          defaultValue === 'bankMonthlyStatement'
            ? statementsConfirmFlag || handleVal((uploadParams as any)[defaultValue], defaultValue)
            : handleVal((uploadParams as any)[defaultValue], defaultValue);
        return !val;
      }).length;
    };
    return [
      {
        key: '1',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={userIcon} width={22} />
            <div> {intl.formatMessage({ id: 'home.user_infos' })}</div>
          </Flex>
        ),
        children: (
          <div>
            {supplementList &&
            supplementList?.filter((item) => ['1'].includes(item.positionId))?.length > 0 ? (
              <StepOne span={6} form={form} isCenter />
            ) : null}
            {supplementList &&
            supplementList?.filter((item) => ['2'].includes(item.positionId))?.length > 0 ? (
              <StepLive
                topTitle={livingSituationList?.find((item) => item.value == livingSituation)?.name}
                steps={2}
                span={6}
                form={form}
                isCenter
              />
            ) : null}
          </div>
        ),
        extra: genExtra(
          returnNumber(supplementList?.filter((item) => ['1', '2'].includes(item.positionId))) || 0,
        ),
        forceRender: true,
      },
      {
        key: '3',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={workIcon} width={22} />
            <div> {intl.formatMessage({ id: 'home.work_info' })}</div>
          </Flex>
        ),
        children: (
          <div>
            <StepTwo
              topTitle={occupationList?.find((item) => item.value == occupation)?.name}
              span={6}
              isCenter
              steps={2}
              form={form}
            />
            {/* {renderBtn('3')} */}
          </div>
        ),
        extra: genExtra(
          returnNumber(supplementList?.filter((item) => ['3'].includes(item.positionId))) || 0,
        ),
        forceRender: true,
      },
      {
        key: '4',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={moneyIcon} width={22} />
            <div> {intl.formatMessage({ id: 'home.user_price' })}</div>
          </Flex>
        ),
        children: (
          <div>
            <StepThree span={6} isCenter form={form} />
          </div>
        ),
        extra: genExtra(
          returnNumber(supplementList?.filter((item) => ['4'].includes(item.positionId))) || 0,
        ),
        forceRender: true,
      },
      {
        key: '5',
        label: (
          <Flex gap={8} align="center" style={{ fontSize: 15, fontWeight: 700 }}>
            <img src={imgIcon} width={22} />
            <div> {intl.formatMessage({ id: 'center.upload_data' })}</div>
          </Flex>
        ),
        children: (
          <>
            <UploadList filterList={filterList} />
            {/* {renderBtn('5')} */}
          </>
        ),
        extra: genExtra(renderImgNumber() || 0),
        forceRender: true,
      },
    ].filter((item) => {
      if (item.key == '1') {
        return ids?.includes('1') || ids?.includes('2');
      }
      return ids?.includes(item.key.toString());
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    supplementList,
    intl,
    form,
    filterList,
    value,
    uploadParams,
    occupationList,
    livingSituationList,
  ]);
  const { merchantLogo, merchantName, applyNum, passNum, passRate, productName } =
    productInfo || {};

  const name = useMemo(() => {
    const type = productInfo?.productType;
    return productType?.find((item) => item.value === type)?.name || '';
  }, [productInfo, productType]);

  const { xScoreAmount } = user || {};

  const tips = () => {
    message.error({ content: intl.formatMessage({ id: 'home.write_all' }), key: 1 });
  };
  return (
    <>
      <Helmet>
        <title>{intl.formatMessage({ id: 'home.meta_title' })}</title>
      </Helmet>
      <Col className="center supplement">
        <Layout bgImg={banner}>
          <Col className="center_top">
            <Col
              className="center_warrper"
              style={{ overflow: 'hidden', display: 'block', padding: isEn ? '25px 0 70px 0' : '' }}
            >
              <TopInfo xScoreAmount={xScoreAmount} />
            </Col>
          </Col>
        </Layout>

        <div className="supplement_warrper">
          <Card className="supplement_card common">
            <div className="supplement_card_top">
              <Flex justify="space-between">
                <Col style={{ fontSize: 14, color: ' rgba(255, 255, 255, 0.6)' }}>
                  {intl.formatMessage({ id: 'center.applying' })}
                </Col>
                <Col style={{ color: '#fff' }}>
                  {intl.formatMessage(
                    { id: 'center.info' },
                    {
                      apply_num: <span className="supplement_card_top_word">{applyNum}</span>,
                      pass_num: <span className="supplement_card_top_word">{passNum}</span>,
                      pass_rate: <span className="supplement_card_top_word">{passRate}%</span>,
                    },
                  )}
                </Col>
              </Flex>
              <Col>
                <Space align="center" size={8} style={{ margin: '6px 0' }}>
                  <Col style={{ padding: '3px', background: '#FFFFFF', borderRadius: 4 }}>
                    <img src={merchantLogo} height={23} />
                  </Col>
                  <Col style={{ fontSize: 24, color: '#fff', fontWeight: 700 }}>{productName}</Col>
                  <Col style={{ fontSize: 24, color: '#fff', fontWeight: 700 }}>{merchantName}</Col>
                  <Col
                    style={{
                      padding: '4px 10px',
                      background: 'rgba(255, 255, 255, 0.2)',
                      color: '#fff',
                      fontSize: 14,
                      borderRadius: 4,
                    }}
                  >
                    {name}
                  </Col>
                </Space>
                <Col style={{ fontSize: 14, color: 'rgba(255, 255, 255, 0.6)' }}>
                  {intl.formatMessage({ id: 'center.tips' }, { type: name })}
                </Col>
              </Col>
            </div>
            <div className="supplement_card_content">
              <Col>
                <Col style={{ color: '#333', fontSize: 18, fontWeight: 'bold', marginBottom: 8 }}>
                  {intl.formatMessage(
                    { id: 'center.data_num' },
                    {
                      num: (
                        <span style={{ color: '#0270DF', margin: '0 4px' }}>
                          {supplementList?.length}
                        </span>
                      ),
                    },
                  )}
                </Col>
                {/* {supplementList && supplementList?.length > 0 ? (
                  <Space align="center" wrap size={[32, 5]}>
                    {supplementList?.map((item) => {
                      const { key, keyDesc, keyDescEn } = item;
                      return (
                        <Flex align="center" key={key} gap={8}>
                          <img width={10} src={circle} />
                          <div style={{ fontSize: 14, color: '#999' }}>
                            {isEn ? keyDescEn : keyDesc}
                          </div>
                        </Flex>
                      );
                    })}
                  </Space>
                ) : null} */}
              </Col>
              <div
                style={{
                  margin: '23px 0 16px 0',
                  color: '#333',
                  fontWeight: 700,
                  fontSize: 20,
                }}
              >
                {intl.formatMessage({ id: 'center.base' })}
              </div>
              <Form
                requiredMark={false}
                labelCol={{ span: 0 }}
                onFinish={async (values) => {
                  const { mobile, loanInfo, birthday, graduationTime, ...rest } = values;
                  const obj: any = {};
                  let submit = true;
                  if (filterList && filterList?.length > 0) {
                    const {
                      idCard: { back, front },
                      insuranceProof,
                      statementsConfirmFlag,
                    } = uploadParams;
                    filterList?.map((item) => {
                      const value = item.defaultValue;
                      if (value === 'idCard') {
                        if (!(front && back)) {
                          submit = false;
                          tips();
                        }
                        obj.idCardImg = front;
                        obj.idCardImg1 = back;
                      } else if (value === 'insuranceProof') {
                        if (insuranceProof.length <= 0) {
                          submit = false;
                          tips();
                        }
                        const insuranceProofValue = JSON.stringify(
                          insuranceProof.map((item: any) => {
                            const { urls, ...rest } = item as any;
                            return {
                              ...rest,
                              urls: getImgUrl(urls),
                            };
                          }),
                        );
                        obj.insuranceProof = insuranceProofValue;
                      } else {
                        if (value == 'bankMonthlyStatement') {
                          obj.statementsConfirmFlag = statementsConfirmFlag;
                          if (!(getImgUrl(uploadParams[value]) || statementsConfirmFlag)) {
                            submit = false;
                            tips();
                          }
                        } else if (!getImgUrl(uploadParams[value])) {
                          submit = false;
                          tips();
                        }
                        obj[value] = getImgUrl(uploadParams[value]);
                      }
                      // 获取额外信息
                    });
                  }

                  if (submit) {
                    setLoading(true);
                    const fn = order ? editOrder : editPage;
                    try {
                      const { message: msgs } = await fn({
                        ...rest,
                        ...(loanInfo ? { loanInfo: JSON.stringify(loanInfo) } : {}),
                        ...(birthday ? { birthday: dayjs(birthday).format('YYYY-MM-DD') } : {}),
                        ...(graduationTime
                          ? { graduationTime: dayjs(graduationTime).format('YYYY-MM-DD') }
                          : {}),
                        ...obj,
                        ...(orderId ? { orderId } : {}),
                      });
                      //  从我的贷款过来 只提交
                      if (order) {
                        message.success(msgs);
                        jumpUrl('/center?index=0');
                      } else {
                        // 提交订单
                        const { data } = await handleGetToken();
                        const { code, message: msg } = await handleApplyOrder({
                          apiToken: data,
                          pid: id?.toString() || '',
                          loanAmount,
                          loanTerm,
                        });
                        if (code === '100200') {
                          setVisible(true);
                          message.success(msg);
                          // 获取最新的数据
                          run();
                        }
                      }
                      setLoading(false);
                    } catch {
                      setLoading(false);
                    }
                  }
                }}
                onFinishFailed={() => {
                  message.error(intl.formatMessage({ id: 'home.write_all' }));
                }}
                layout="vertical"
                className="info_right_form supplement_form"
                form={form}
              >
                <Collapse
                  expandIcon={(panelProps) => {
                    const { isActive } = panelProps;
                    return (
                      <img
                        style={{
                          transition: 'all .5s',
                          transform: `rotate(${isActive ? 180 : 0}deg)`,
                        }}
                        src={arrow}
                        width={25}
                      />
                    );
                  }}
                  expandIconPosition="end"
                  bordered={false}
                  items={items}
                />
                <div className="supplement_card_btn">{renderBtn('center.submit_supplement')}</div>
              </Form>
            </div>
          </Card>
        </div>
        <Col className="center_bottom" />
      </Col>
      <ApplySucModal
        visible={visible}
        handleCancel={() => {
          setVisible(false);
        }}
        data={productInfo || {}}
      />
    </>
  );
};

export default Supplement;
